package com.ysstech.common.config;

import com.ysstech.common.exception.BusinessException;
import com.ysstech.common.util.fileutil.FileUtil;
import com.ysstech.common.util.imgutil.ImageUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

@Configuration
@Slf4j
public class UploadFileConfig {
    private static final int MAX_POST_IMAGE_SIZE = 10;
    @Value("${file.uploadFolder}")
    private String uploadFolder;
    @Value("${file.accessPath}")
    private String accessPath;
    @Value("${yss.eureka.ip}")
    private String ip;
    @Value("${yss.gateway.port}")
    private String port;


    /**
     * 上传到当前服务器
     *
     * @param multipartFile
     * @return
     * @throws Exception
     */
    public String uploadImg(MultipartFile multipartFile) throws Exception {
        if (multipartFile.isEmpty()) {
            throw new BusinessException("请选择图片");
        }
        //检查格式
        String isRealImageStr = ImageUtil.isRealImage(multipartFile.getBytes());
        if (null == isRealImageStr) {
            throw new BusinessException("上传的不是图片，请重新选择上传！");
        }
        //检查文件大小
        double imageSize = (double) multipartFile.getSize() / 1024 / 1024;
        NumberFormat nf = new DecimalFormat("0.00");
        log.info("图片大小：" + Double.parseDouble(nf.format(imageSize)) + "M");
        if (imageSize > MAX_POST_IMAGE_SIZE) {
            throw new BusinessException("请上传" + MAX_POST_IMAGE_SIZE + "M以内图片");
        }
        String fileName = multipartFile.getOriginalFilename();//文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));//后缀名
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/");
        String format = simpleDateFormat.format(new Date());
        String path = uploadFolder + format; //文件存储位置
        fileName = UUID.randomUUID() + suffixName;//图片名
        String imageUrl = path + "/" + fileName;//图片的url
        log.info("图片URL：" + imageUrl);
        File dest = new File(imageUrl);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        multipartFile.transferTo(dest);
        path = "http://" + ip + ":" + port;
        return path + accessPath + format + "/" + fileName;
    }


    //ftp服务器ip地址
    @Value("${custom.config.file-server.ip}") // 相关配置放在application.properties 中
    private String FTP_ADDRESS;
    //端口号
    @Value("${custom.config.file-server.port}")
    private Integer FTP_PORT;
    //用户名
    @Value("${custom.config.file-ftp-user}")
    private String FTP_USERNAME;
    //密码
    @Value("${custom.config.file-ftp-password}")
    private String FTP_PASSWORD;
    //图片路径
    @Value("${custom.config.file-savepath}")
    private String FTP_BASEPATH;

    //根据当前文件生成 文件夹


    public String upload(MultipartFile multipartFile) throws Exception {
        StringBuilder url = new StringBuilder();
        FileInputStream inputStream = null;
        FTPClient ftp = new FTPClient();
        ftp.setControlEncoding("GBK");
        try {
            int reply;
            ftp.connect(FTP_ADDRESS, FTP_PORT);// 连接FTP服务器
            ftp.login(FTP_USERNAME, FTP_PASSWORD);// 登录
            reply = ftp.getReplyCode();
            ftp.enterLocalPassiveMode();//开启被动模式，否则文件上传不成功，也不报错
            DateFormat format = new SimpleDateFormat("yyyy/MM/dd/");
            String timePath = format.format(new Date());
            String saveDir = FTP_BASEPATH + timePath;
            url.append(saveDir);
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            createDir(ftp, saveDir);
            //ftp.makeDirectory(saveDir);
            //ftp.changeWorkingDirectory(FTP_BASEPATH);
            String originName = multipartFile.getOriginalFilename();//文件名
            originName = System.currentTimeMillis() + originName.substring(originName.lastIndexOf('.'));
            url.append(originName);
            inputStream = new FileInputStream(FileUtil.MultipartFileToFile(multipartFile));
            ftp.storeFile(originName, inputStream);
            inputStream.close();
            ftp.logout();

        } catch (IOException e) {
            throw new RuntimeException("文件上传失败");
        } finally {
            if (ftp.isConnected()) {
                ftp.disconnect();
            }
        }
        return url.toString();
    }
    // 创建文件夹，并切换到该文件夹
    // 比如： hello/test
    //最终会切换到test 文件夹返回


    private void createDir(FTPClient client, String path) throws IOException {
        String[] dirs = path.split("/");
        for (String dir : dirs) {
            if (StringUtils.isEmpty(dir)) {
                continue;
            }
            if (!client.changeWorkingDirectory(dir)) {
                client.makeDirectory(dir);
            }
            client.changeWorkingDirectory(dir);
        }
    }


}
